package archer.application.elastic.mock.core.service.user;

import archer.application.elastic.mock.core.constant.Constant;
import archer.application.elastic.mock.core.entity.user.User;
import archer.application.elastic.mock.core.subject.ArcherUser;
import archer.framework.common.service.BaseService;
import archer.framework.protocol.result.ExecuteResult;
import archer.framework.security.token.Token;
import archer.framework.security.utils.SubjectUtils;
import org.springframework.stereotype.Component;

/**
 * 用户父类Service
 *
 * @author christ
 * @date 2016/6/3
 */
@Component
public class UserService extends BaseService {

    /**
     * 用登录用户名登录
     *
     * @param loginName
     * @param password
     * @param type
     * @return
     */
    public ExecuteResult loginNameLogin(String loginName, String password, String type) {

        return login(null, loginName, null, password, type);
    }

    /**
     * 登录
     *
     * @param mobile
     * @param password
     * @param type
     * @return
     */
    public ExecuteResult login(String mobile, String loginName, String email, String password, String type) {

        if (isEmpty(password)) {
            return paramNull("密码不能为空");
        }

        if (isEmpty(type)) {
            return paramNull("用户类型不能为空");
        }

        if (isEmpty(mobile) && isEmpty(loginName) && isEmpty(email)) {
            // 最少三选一
            return paramNull("用户凭证不能为空");
        }

        User user = null;
        // 根据手机号查
        if (isNotEmpty(mobile)) {
            user = User.find
                    .query()
                    .where()
                    .eq("mobile", mobile)
                    .eq("password", password)
                    .eq("type", type)
                    .findUnique();
        }

        if (isEmpty(user) && isNotEmpty(loginName)) {
            user = User.find
                    .query()
                    .where()
                    .eq("loginName", loginName)
                    .eq("password", password)
                    .eq("type", type)
                    .findUnique();
        }

        if (isEmpty(user) && isNotEmpty(email)) {
            user = User.find
                    .query()
                    .where()
                    .eq("email", email)
                    .eq("password", password)
                    .eq("type", type)
                    .findUnique();
        }

        if (isEmpty(user)) {
            return paramInvalidate("用户名或密码错误");
        }

        if (Constant.UserStatus.DISABLE.equals(user.getStatus())) {
            return accessDenied("当前用户已被禁用");
        }

        // token 处理
        Token token = SubjectUtils.bindAssociatedToken(new ArcherUser().setUserId(user.getId()));

        return success(asMap("token", token.getId(), "userId", user.getId(), "loginName", user.getLoginName()));
    }

}
